import React, { useState } from 'react';
import { Table, Button, Tag, Tooltip, message } from 'antd';
import { EyeOutlined, InfoCircleOutlined, IdcardOutlined, CodeOutlined, ApiOutlined, BranchesOutlined, ScanOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { type UnitMetricsData } from '../../../services/metrics';
import { getUnit } from '../../../services/unit';

// 单元信息Tooltip组件
const UnitInfoTooltip: React.FC<{ unitId: string }> = ({ unitId }) => {
    const navigate = useNavigate();
    const [unitConfig, setUnitConfig] = useState<any>(null);
    const [loading, setLoading] = useState(false);
    const [visible, setVisible] = useState(false);

    const fetchUnitConfig = async () => {
        if (unitConfig || loading) return;

        setLoading(true);
        try {
            const response = await getUnit(unitId);
            if (response.code === 0) {
                setUnitConfig(response.data);
            }
        } catch (error) {
            console.error('获取单元配置失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleVisibleChange = (visible: boolean) => {
        setVisible(visible);
        if (visible) {
            fetchUnitConfig();
        }
    };

    const handleViewUnit = () => {
        navigate(`/unit/${unitId}`);
    };

    const tooltipContent = loading ? (
        <div style={{ padding: '12px', textAlign: 'center', color: '#666' }}>
            <span>加载中...</span>
        </div>
    ) : unitConfig ? (
        <div style={{ maxWidth: '480px', padding: '4px' }}>
            <div style={{
                marginBottom: '12px',
                paddingBottom: '8px',
                borderBottom: '1px solid #e8e8e8',
                display: 'flex',
                alignItems: 'center',
                gap: '6px'
            }}>
                <InfoCircleOutlined style={{ color: '#1890ff', fontSize: '14px' }} />
                <span style={{ fontWeight: '600', fontSize: '14px', color: '#262626' }}>
                    单元配置信息
                </span>
            </div>

            <div style={{ marginBottom: '12px' }}>
                <div style={{
                    fontSize: '11px',
                    color: '#8c8c8c',
                    marginBottom: '6px',
                    fontWeight: '500',
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px'
                }}>
                    基本信息
                </div>
                <div style={{
                    background: '#fafafa',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    lineHeight: '1.8'
                }}>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>单元ID</span>
                        <span style={{ color: '#262626', fontWeight: '500', flex: 1 }}>{unitConfig.unitId || '-'}</span>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>应用ID</span>
                        <span style={{ color: '#262626' }}>{unitConfig.appId || '-'}</span>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>单元类型</span>
                        <span style={{ color: '#262626' }}>{unitConfig.unitType || '-'}</span>
                    </div>
                    <div style={{ display: 'flex' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>归属团队</span>
                        <span style={{ color: '#262626' }}>{unitConfig.ownTeam || '-'}</span>
                    </div>
                </div>
            </div>

            <div style={{ marginBottom: '12px' }}>
                <div style={{
                    fontSize: '11px',
                    color: '#8c8c8c',
                    marginBottom: '6px',
                    fontWeight: '500',
                    textTransform: 'uppercase',
                    letterSpacing: '0.5px'
                }}>
                    Git仓库
                </div>
                <div style={{
                    background: '#fafafa',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '12px',
                    lineHeight: '1.8'
                }}>
                    <div style={{ marginBottom: '6px' }}>
                        <div style={{ color: '#8c8c8c', marginBottom: '2px' }}>仓库地址</div>
                        <div style={{
                            color: '#1890ff',
                            wordBreak: 'break-all',
                            fontSize: '11px',
                            fontFamily: 'Monaco, Consolas, monospace'
                        }}>
                            {unitConfig.gitRepoUrl || '未配置'}
                        </div>
                    </div>
                    <div style={{ display: 'flex', marginBottom: '4px' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>默认分支</span>
                        <Tag color="blue" style={{ margin: 0, fontSize: '11px' }}>
                            {unitConfig.defaultBranch || '-'}
                        </Tag>
                    </div>
                    <div style={{ display: 'flex' }}>
                        <span style={{ color: '#8c8c8c', minWidth: '70px', flexShrink: 0 }}>当前分支</span>
                        <Tag color="green" style={{ margin: 0, fontSize: '11px' }}>
                            {unitConfig.currentBranch || '-'}
                        </Tag>
                    </div>
                </div>
            </div>
        </div>
    ) : (
        <div style={{ padding: '12px', textAlign: 'center', color: '#999' }}>
            <span>暂无数据</span>
        </div>
    );

    return (
        <Tooltip
            title={tooltipContent}
            placement="right"
            overlayStyle={{ maxWidth: '520px' }}
            overlayInnerStyle={{
                backgroundColor: '#fff',
                color: '#333',
                boxShadow: '0 4px 16px rgba(0,0,0,0.12)',
                borderRadius: '6px',
                padding: '12px'
            }}
            color="#fff"
            open={visible}
            onOpenChange={handleVisibleChange}
        >
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: '4px' }}>
                <Button
                    type="link"
                    onClick={handleViewUnit}
                    style={{ padding: 0, fontWeight: '500' }}
                >
                    {unitId}
                </Button>
                <InfoCircleOutlined
                    style={{
                        fontSize: '13px',
                        color: '#1890ff',
                        cursor: 'pointer',
                        transition: 'all 0.2s',
                    }}
                    onMouseEnter={(e) => {
                        e.currentTarget.style.color = '#40a9ff';
                        e.currentTarget.style.transform = 'scale(1.1)';
                    }}
                    onMouseLeave={(e) => {
                        e.currentTarget.style.color = '#1890ff';
                        e.currentTarget.style.transform = 'scale(1)';
                    }}
                />
            </span>
        </Tooltip>
    );
};

interface UnitListTableProps {
    units: UnitMetricsData[];
    loading?: boolean;
    showActions?: boolean;
    onTriggerScan?: (unitId: string) => void;
    triggeringUnitId?: string | null;
    pagination?: any;
    onChange?: (pagination: any, filters: any, sorter: any) => void;
    scroll?: { x?: number | string; y?: number | string };
}

const UnitListTable: React.FC<UnitListTableProps> = ({
    units,
    loading = false,
    showActions = true,
    onTriggerScan,
    triggeringUnitId,
    pagination,
    onChange,
    scroll
}) => {
    const navigate = useNavigate();

    const handleViewUnit = (unitId: string) => {
        navigate(`/unit/${unitId}`);
    };

    const columns = [
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#1890ff'
                }}>
                    <IdcardOutlined style={{ fontSize: '14px' }} />
                    <span>基本信息</span>
                </div>
            ),
            children: [
                {
                    title: '单元ID',
                    dataIndex: 'unitId',
                    key: 'unitId',
                    width: 180,
                    fixed: 'left' as const,
                    render: (text: string) => <UnitInfoTooltip unitId={text} />,
                },
                {
                    title: '应用ID',
                    dataIndex: 'appId',
                    key: 'appId',
                    width: 120,
                    render: (text: string) => text || '-',
                },
                {
                    title: '单元类型',
                    dataIndex: 'unitType',
                    key: 'unitType',
                    width: 100,
                    render: () => '后端服务',
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#52c41a'
                }}>
                    <CodeOutlined style={{ fontSize: '14px' }} />
                    <span>代码信息</span>
                </div>
            ),
            children: [
                {
                    title: '代码行',
                    dataIndex: 'totalCodeLines',
                    key: 'totalCodeLines',
                    width: 100,
                    sorter: true,
                    render: (lines: number) => {
                        if (!lines) return '0';
                        return lines > 1000 ? `${(lines / 1000).toFixed(1)}K` : lines.toString();
                    },
                },
                {
                    title: '文件数',
                    dataIndex: 'totalFiles',
                    key: 'totalFiles',
                    width: 80,
                    sorter: true,
                    render: (files: number) => files || 0,
                },
                {
                    title: '代码重复率',
                    dataIndex: 'duplicationPercentage',
                    key: 'duplicationPercentage',
                    width: 100,
                    sorter: true,
                    render: (percentage: number) => {
                        if (percentage === null || percentage === undefined) return '-';
                        const value = typeof percentage === 'number' ? percentage : parseFloat(percentage);
                        return isNaN(value) ? '-' : `${value.toFixed(1)}%`;
                    },
                },
                {
                    title: '圈复杂度',
                    dataIndex: 'totalCyclomaticComplexity',
                    key: 'totalCyclomaticComplexity',
                    width: 100,
                    sorter: true,
                    align: 'right' as const,
                    render: (total: number) => {
                        if (total === null || total === undefined) return '-';
                        return (
                            <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '14px' }}>
                                {total}
                            </span>
                        );
                    },
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#fa8c16'
                }}>
                    <ApiOutlined style={{ fontSize: '14px' }} />
                    <span>接口信息</span>
                </div>
            ),
            children: [
                {
                    title: '总接口数量',
                    dataIndex: 'totalApiCount',
                    key: 'totalApiCount',
                    width: 100,
                    align: 'right' as const,
                    sorter: true,
                    render: (count: number) => (
                        <span style={{ fontWeight: '600', color: '#1890ff', fontSize: '14px' }}>
                            {count || 0}
                        </span>
                    )
                },
                {
                    title: '疑似废弃接口',
                    dataIndex: 'suspectedDeprecatedApiCount',
                    key: 'suspectedDeprecatedApiCount',
                    width: 140,
                    align: 'center' as const,
                    sorter: true,
                    render: (count: number, record: UnitMetricsData) => {
                        if (record.apmDataStatus !== 'AVAILABLE') {
                            return <span style={{ color: '#d9d9d9' }}>--</span>;
                        }

                        const total = (record as any).totalApiCount || 0;
                        const ratio = total > 0 ? ((count || 0) / total * 100).toFixed(1) : '0.0';
                        const isHigh = parseFloat(ratio) > 20;

                        return (
                            <span style={{ fontFamily: 'monospace', fontSize: '12px' }}>
                                <span style={{
                                    fontWeight: '600',
                                    color: isHigh ? '#ff4d4f' : '#52c41a',
                                    fontSize: '14px'
                                }}>
                                    {count || 0}
                                </span>
                                <span style={{ margin: '0 4px', color: '#999' }}>/</span>
                                <span style={{ fontSize: '11px', color: '#999' }}>
                                    {ratio}%
                                </span>
                            </span>
                        );
                    }
                },
            ]
        },
        {
            title: (
                <div style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '6px',
                    padding: '4px 0',
                    fontWeight: '600',
                    fontSize: '13px',
                    color: '#722ed1'
                }}>
                    <BranchesOutlined style={{ fontSize: '14px' }} />
                    <span>仓库信息</span>
                </div>
            ),
            children: [
                {
                    title: '仓库活跃度',
                    dataIndex: 'commitCountLastYear',
                    key: 'commitCountLastYear',
                    width: 140,
                    align: 'center' as const,
                    sorter: true,
                    render: (_: any, record: UnitMetricsData) => {
                        const level = record.repoActivityLevel || 'UNKNOWN';
                        const commitCount = record.commitCountLastYear || 0;

                        const configs: { [key: string]: { text: string; color: string } } = {
                            'HIGH': { text: '高活跃', color: 'green' },
                            'MEDIUM': { text: '中活跃', color: 'orange' },
                            'LOW': { text: '低活跃', color: 'red' },
                            'UNKNOWN': { text: '未知', color: 'default' }
                        };
                        const config = configs[level] || configs['UNKNOWN'];

                        return (
                            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
                                <Tag color={config.color} style={{ margin: 0 }}>{config.text}</Tag>
                                {commitCount > 0 && (
                                    <span style={{ fontSize: '11px', color: '#999', whiteSpace: 'nowrap' }}>
                                        {commitCount}次/年
                                    </span>
                                )}
                            </div>
                        );
                    }
                },
            ]
        },
        {
            title: '数据就绪情况',
            key: 'dataReadiness',
            width: 160,
            render: (_: any, record: UnitMetricsData) => {
                const getStatusColor = (status: string) => {
                    switch (status) {
                        case 'AVAILABLE':
                            return '#52c41a';
                        case 'UNAVAILABLE':
                            return '#ff4d4f';
                        case 'UNKNOWN':
                        default:
                            return '#d9d9d9';
                    }
                };

                const getStatusIcon = (status: string) => {
                    switch (status) {
                        case 'AVAILABLE':
                            return '●';
                        case 'UNAVAILABLE':
                            return '●';
                        case 'UNKNOWN':
                        default:
                            return '○';
                    }
                };

                const dataTypes = [
                    { key: 'jar', label: 'JAR', status: record.jarDataStatus },
                    { key: 'git', label: 'Git', status: record.gitDataStatus },
                    { key: 'apm', label: 'APM', status: record.apmDataStatus },
                    { key: 'sa', label: 'SA', status: record.saDataStatus },
                ];

                return (
                    <div style={{ display: 'flex', gap: '6px', alignItems: 'center', flexWrap: 'wrap' }}>
                        {dataTypes.map(({ key, label, status }) => (
                            <span
                                key={key}
                                style={{
                                    display: 'inline-flex',
                                    alignItems: 'center',
                                    gap: '2px',
                                    fontSize: '11px',
                                    color: getStatusColor(status || 'UNKNOWN'),
                                    fontWeight: '500'
                                }}
                            >
                                <span>{getStatusIcon(status || 'UNKNOWN')}</span>
                                <span>{label}</span>
                            </span>
                        ))}
                    </div>
                );
            },
        },
        ...(showActions ? [{
            title: '操作',
            key: 'action',
            width: 120,
            fixed: 'right' as const,
            render: (_: any, record: UnitMetricsData) => (
                <div style={{ display: 'flex', gap: '8px' }}>
                    <Button
                        type="text"
                        size="small"
                        icon={<EyeOutlined />}
                        onClick={() => handleViewUnit(record.unitId)}
                        title="查看详情"
                    />
                    {onTriggerScan && (
                        <Button
                            type="text"
                            size="small"
                            icon={<ScanOutlined />}
                            loading={triggeringUnitId === record.unitId}
                            onClick={() => onTriggerScan(record.unitId)}
                            title="触发扫描"
                        />
                    )}
                </div>
            ),
        }] : []),
    ];

    return (
        <Table
            columns={columns}
            dataSource={units}
            loading={loading}
            pagination={pagination || {
                pageSize: 20,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                    `显示第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
            }}
            onChange={onChange}
            rowKey="unitId"
            scroll={scroll || { x: 1600 }}
            size="middle"
        />
    );
};

export default UnitListTable;
